<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;


/**
 * 礼物接口
 */
class Gift extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $giftLogic = null; //礼物逻辑类

    // protected $limitFields = 'name';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Gift();
        $this->giftLogic = new \app\common\logic\GiftLogic();
    }


    /**
     * 设置价格，备注
     */
    public function updateGift()
    {
        $order_sn = $this->request->request('order_sn');
        $is_show = $this->request->request('is_show', 0);
        $note = $this->request->request('note', '');

        $this->giftLogic->setOrderSn($order_sn);
        $this->giftLogic->setUserId($this->auth->id);
        $giftIds = $this->giftLogic->getGiftIdsByOrderSn();
        if ($giftIds['code'] == 1) {
            foreach ($giftIds['data'] as $k => $v) {
                $res = Db::name('gift')->where(['id' => $v])->update(['is_show_price' => $is_show, 'note' => $note]);

            }

            if ($res !== false) {
                $this->success('设置成功');
            } else {
                $this->error('设置失败');
            }


        } else {
            $this->error($giftIds['msg']);
        }
    }

    /**
     * 发送给好友页面
     * $order_sn 订单号 （order_sn 或 master_order_sn）
     */
    public function gift()
    {
        $order_sn = $this->request->request('order_sn');
        $giftLogic = new \app\common\logic\GiftLogic();
        $giftLogic->setOrderSn($order_sn);
        $giftLogic->setUserId($this->auth->id);
        $gift = $giftLogic->getGiftByOrderSn();
        if ($gift['code'] == 1) {
            $giftGoodsId = [];
            $giftData = [];

            //合并同一商品的礼物
            foreach ($gift['data'] as $k => $v) {
                if (!in_array($v['goods_id'], $giftGoodsId)) {
                    array_push($giftGoodsId, $v['goods_id']);
                    array_push($giftData, $v);
                } else {
                    continue;
                }
            }

            $data = [
                'send_user_id' => $this->auth->id,
                'giftList' => $giftData
            ];
            $this->success('', $data);
        } else {
            $this->error($gift['msg']);
        }
    }


    /**
     * 生成分享图片页面信息
     *
     */
    public function shareImage()
    {
        $order_sn = $this->request->request('order_sn');
        $user = Db::name('user')->where('id', $this->auth->id)->field('id,nickname,avatar')->find();
        $giftLogic = new \app\common\logic\GiftLogic();
        $giftLogic->setOrderSn($order_sn);
        $giftLogic->setUserId($this->auth->id);
        $gift = $giftLogic->getGiftByOrderSn();

        //生成二维码
        $wx = new \wechat\Wx();
        $wxqrce = $wx->getQrCode($this->auth->id, $order_sn);
        if ($wxqrce['code'] == 0) {
            $this->error($wxqrce['msg']);
        }

        if ($gift['code'] == 1) {
            $giftInfo = $gift['data'][0];

            $data = [
                'user' => $user,
                'giftInfo' => $giftInfo,
                'image' => $wxqrce['data'],
//                'image' => '/uploads/20180523/19c3ebc8749261df572ec50929cc5593.jpg'
            ];
            $this->success('', $data);
        } else {
            $this->error($gift['msg']);
        }
    }



    /**
     *拆礼物页面信息
     */
    public function chai()
    {
        $send_user_id = $this->request->request('send_user_id');
        $zhuan_user_id = $this->request->request('zhuan_user_id', 0);
        $zhuan_user_id ? $user_id = $zhuan_user_id : $user_id = $send_user_id;
        $user = Db::name('user')->where(['id' => $user_id])->field('nickname,avatar')->find();
        $this->success('', $user);
    }


    /**
     * 拆礼物提交
     */
    public function robgift()
    {
        $order_sn = $this->request->request('order_sn');
        $send_user_id = $this->request->request('send_user_id');
        $giftLogic = new \app\common\logic\GiftLogic();

        $giftLogic->setOrderSn($order_sn);
        $giftLogic->setUserId($send_user_id);

        $res = $giftLogic->addRobGift($this->auth->id);
        if ($res['code'] == 1) {
            $data = [
                'id' => $res['data']['id'],
                'pid' => $res['data']['pid'],
                'order_sn' => $order_sn,
                'send_user_id' => $send_user_id
            ];

            $this->success($res['msg'], $data);

        } else {
            $this->error($res['msg']);
        }
    }

    /**
     * 收礼成功页面
     * @param order_sn: 订单号
     * @param send_user_id: 送礼人user_id
     * @param type: 送礼类型
     * @param ids: 拆开新生成的礼物id
     * @param pid: 送礼礼物id
     *
     */
    public function giftSuccess()
    {
        $order_sn = $this->request->request('order_sn');
        $send_user_id = $this->request->request('send_user_id'); //送礼人user_id
        $ids = $this->request->request('ids');
        $type = $this->request->request('type');
        $idsArr = explode(',',$ids);


        $giftLogic = new \app\common\logic\giftLogic();
        $giftLogic->setOrderSn($order_sn);
        $giftLogic->setUserId($send_user_id);
        $data = [];

        //送一人
        foreach($idsArr as $k => $v){
            //送礼人礼物信息
            $pid = Db::name('gift')->where('id',$v)->value('pid');
            $send_gift = \app\common\model\Gift::get($pid);
            $follow_user = $giftLogic->getFollowUser();
            $send_user = Db::name('user')->where('id', $send_gift['user_id'])->field('id,nickname,avatar')->find();
            $giftOrder = Db::name('order')->where('id',$send_gift['order_id'])->find();
            $data[$k] = [
                'id' => $v,
                'order_sn' => $order_sn,
                'send_gift_info' => [
                    'goods_name' => $send_gift->goods['name'],
                    'image' => $send_gift->goods['image'],
                    'is_show_price' => $send_gift['is_show_price'],
                    'price' => $send_gift['price'],
                    'note' => $send_gift['note'],
                    'shop_price' => $send_gift->goods['shop_price'],
                    'goods_num' => $giftOrder['goods_num']
                ],
                'send_user' => $send_user,
                'follow_user' => $follow_user
            ];
        }

        $data = ['user_id' => $this->auth->id,'data' => $data ];

        $this->success('', $data);
    }



    /**
     * 个人中心接收礼物列表
     * @param giftType : 0=赠送礼物未领取列表, 1=赠送礼物已领取列表，2=接收礼物列表，3=提货记录列表，4=提现记录列表
     */
    public function giftList()
    {

        $giftType = $this->request->request('giftType', 0);
        $giftWhere = [];
        if ($giftType == 2) {
            //接收
            $giftWhere = ['status' => 1];

        } elseif ($giftType == 1) {
            //赠送已领取
            $giftWhere = ['status' => 5, 'type' => 1];
        } elseif ($giftType == 3) {
            //提货记录
            $giftWhere = ['status' => 2];

        } elseif ($giftType == 4) {
            //提现记录
            $giftWhere = ['status' => 3];

        } else {
            //赠送未领取,giftType = 0

            $giftWhere = ['status' => ['in', '0,4']];
        }

        $this->dataLimit = true;

        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where(function ($query) use ($giftWhere) {
                $query->where($giftWhere);
            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->with('goods')
            ->with('order')
            ->field($field)
            ->where($where)
            ->where(function ($query) use ($giftWhere) {
                $query->where($giftWhere);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        foreach ($list as $k => $v) {
            if ($giftType == 1) {
                //赠送已领取
                $to_user_id = Db::name('gift')->where('pid', $v['id'])->value('user_id');
                $to_user = [];
                if ($to_user_id) {
                    $to_user_info = Db::name('user')->where(['id' => $to_user_id])->field('nickname')->find();
                    $to_user = $to_user_info;
                }
                $list[$k]['to_user'] = $to_user;

            } elseif ($giftType == 2) {
                //接收
                $send_user = [];  //赠送礼物人信息

                if ($v['pid'] > 0) {
                    $send_user_id = Db::name('gift')->where(['id' => $v['pid']])->value('user_id');
                    $send_user_info = Db::name('user')->where(['id' => $send_user_id])->field('id,nickname,avatar')->find();
                    $send_user = $send_user_info;
                    $list[$k]['send_user'] = $send_user;
                }else{
                    //自己买
                    if($v['user_id'] == $this->auth->id){
                        $user = $this->auth->getUserinfo();

                        $send_user1 = ['id' => $user['id'],'nickname' => $user['nickname'], 'avatar' => $user['avatar']];

                    }else{
                        $send_user1 = [];
                    }
                    $list[$k]['send_user'] = $send_user1;

                }


            } elseif ($giftType == 3) {
                //提货记录
                $send_user = [];  //赠送礼物人信息
                if ($v['pid'] > 0) {
                    $send_user_id = Db::name('gift')->where(['id' => $v['pid']])->value('user_id');
                    $send_user_info = Db::name('user')->where(['id' => $send_user_id])->field('id,nickname,avatar')->find();
                    $send_user = $send_user_info;
                }
                $list[$k]['send_user'] = $send_user;


            } elseif ($giftType == 4) {
                //提现记录
                $putforward_fee = Db::name('config')->where(['name' => 'putforward_fee'])->value('value');
                $realforward_fee = ($v['price'] * 100 - $putforward_fee * 100) / 100;
                $realforward_fee = number_format($realforward_fee, 2, '.', '');
                $list[$k]['chengGongTiXian'] = $realforward_fee;

                $send_user = [];  //赠送礼物人信息
                if ($v['pid'] > 0) {
                    $send_user_id = Db::name('gift')->where(['id' => $v['pid']])->value('user_id');
                    $send_user_info = Db::name('user')->where(['id' => $send_user_id])->field('id,nickname,avatar')->find();
                    $send_user = $send_user_info;
                }
                $list[$k]['send_user'] = $send_user;


            } else {
                //赠送未领取


            }
        }

        if ($giftType == 0) {

        }

        $result = array("total" => $total, "rows" => $list);


        $this->success('', $result);

    }


    /**
     * 个人中心礼物赠送列表
     */
    public function sendList(){
        $this->dataLimit = true;
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();
        $giftWhere = ['status' => ['in', '0,4,5']];

        $total = $this->model
            ->where($where)
            ->where(function ($query) use ($giftWhere) {
                $query->where($giftWhere);
            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->with('goods')
            ->with('order')
            ->field($field)
            ->where($where)
            ->where(function ($query) use ($giftWhere) {
                $query->where($giftWhere);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        //处理数据--start
        $giftGoodsId = [];
        $notReceiveGiftData = [];
        $ReceiveGiftData = [];



        foreach($list as $k => $v){

            //合并同一商品的礼物
            if($v['type'] == 2){
                if (!in_array($v['goods_id'], $giftGoodsId)) {
                    array_push($giftGoodsId, $v['goods_id']);
                    array_push($notReceiveGiftData, $v->toArray());

                }


            }else{
                if($v['status'] == 5){
                    array_push($ReceiveGiftData,$v->toArray());
                }else{
                    array_push($notReceiveGiftData, $v->toArray());

                }

            }
        }

        //领取进度
        foreach($notReceiveGiftData as $k => $v){

            if($v['type'] == 2){
                $totalCount = Db::name('gift')->where(['goods_id' => $v['goods_id'],'user_id' => $v['user_id'],'order_sn' => $v['order_sn'], 'status' => ['in','0,4,5']])->count();
                $receiveCount = Db::name('gift')->where(['goods_id' => $v['goods_id'],'user_id' => $v['user_id'],'order_sn' => $v['order_sn'],'status' => '5'])->count();
                $v['totalCount'] = $totalCount;
                $v['receiveCount'] = $receiveCount;
                $notReceiveGiftData[$k]['totalCount'] = $totalCount;
                $notReceiveGiftData[$k]['receiveCount'] = $receiveCount;

                if($receiveCount == $totalCount){
                    array_unshift($ReceiveGiftData,$v);
                    unset($notReceiveGiftData[$k]);

                }
            }

        }
        $notReceiveGiftData = array_values($notReceiveGiftData);


        foreach($ReceiveGiftData as $k => $v){

            //赠送已领取
            $to_user_id = Db::name('gift')->where('pid', $v['id'])->value('user_id');
            $to_user = [];
            if ($to_user_id) {
                $to_user_info = Db::name('user')->where(['id' => $to_user_id])->field('nickname')->find();
                $to_user = $to_user_info;
            }
            $ReceiveGiftData[$k]['to_user'] = $to_user;
        }

        $return = [
            'notReceiveGiftData' => $notReceiveGiftData,
            'ReceiveGiftData' => $ReceiveGiftData
        ];


//        dump($return);exit;


        //处理数据 -- end

        $this->success('',$return);

    }

    /**
     * 礼物详情
     * @param null $ids
     */
    public function giftDetail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $row->goods;
        $row->order;
        $this->success('', $row);
    }


    /**
     * 提货页面
     */
    public function deliverypage($ids = null)
    {
        $gift = $this->model->get($ids);
        if ($gift['status'] != 1) {
            $this->error('礼物状态不允许提现');
        }

        $goodsAttr = Db::name('goods_attr')->field('id,attr_value')->where(['goods_id' => $gift['goods_id']])->select();

        $gift->order;
        $gift->goods;
        $gift->goodsAttrData = $goodsAttr;

        $this->success('', $gift);

    }


    /**
     * delivery putforward
     * 礼物提货
     */
    public function delivery($ids = null)
    {
        $address_id = $this->request->request('address_id');
        $item_id = $this->request->request('item_id', 0);

        $gift = $this->model->get($ids);

        if ($gift['status'] != 1) {
            $this->error('礼物状态不允许提现');
        }
        if (!$address_id) {
            $this->error('收货地址必填哦！');
        }

        $orderM = new \app\common\model\Order();
        $order = $orderM->get($gift['order_id']);
        $order->first_user_id = $order['user_id'];
        $order->user_id = $this->auth->id;
        $order->address_id = $address_id;
        $order->deleted = 0;

        $order->item_id = $item_id;
        $order->user_note = "收礼用户提货";
        $result = $order->save();

        if ($result !== false) {
            $gift->status = 2; //已提货
            $gift->save();

            $this->success('提货成功');

        } else {
            $this->error('提货失败');
        }


    }

    /**
     * 提现页面
     * @param null $ids
     */
    public function putforwardpage($ids = null)
    {
        $row = $this->model->get($ids);
        if ($row['status'] != 1) {
            $this->error('礼物状态不允许提现');
        }
        if (!$row)
            $this->error(__('No Results were found'));
        $row->goods;
        $row->order;
        $putforward_fee = Db::name('config')->where(['name' => 'putforward_fee'])->value('value');
        $realforward_fee = ($row->order['goods_price'] * 100 - $putforward_fee * 100) / 100;
        $realforward_fee = number_format($realforward_fee, 2, '.', '');
        $row['realforward_fee'] = $realforward_fee; //实际提现
        $row['putforward_fee'] = $putforward_fee; //手续费

        $row['tishi'] = \app\common\model\Page::getPagesByCategoryName('礼物折现温馨提示');

        $this->success('', $row);
    }

    /**
     * 礼物提现
     * @param null $ids
     */
    public function putforward($ids = null)
    {
        $name = $this->request->request('name');
        $cardno = $this->request->request('cardno/d');
        $account = $this->request->request('account');

        $row = $this->model->get($ids);
        if ($row['status'] != 1) {
            $this->error('礼物状态不允许提现');
        }

        $tixianM = new \app\common\model\Tixian();
        $data = [
            'name' => $name,
            'cardno' => $cardno,
            'user_id' => $this->auth->id,
            'createtime' => time(),
            'account' => $account,
            'note' => "用户申请礼物折现"
        ];
        $result = $tixianM->save($data);
        if ($result) {
            //修改礼物状态
            $row->status = 3;
            $row->save();

            $this->success('礼物折现申请成功');
        } else {
            $this->error('礼物折现申请失败');
        }
    }

    /**
     * 送好友礼物分享回调
     * order_sn
     */
    public function shareCallback()
    {
        $order_sn = $this->request->request('order_sn');
        $giftLogic = new \app\common\logic\GiftLogic();
//        $giftLogic->getGiftIdsByOrderSn();

        $giftLogic->setOrderSn($order_sn);
        $giftLogic->setUserId($this->auth->id);
        $giftIds = $giftLogic->getGiftIdsByOrderSn();
        if ($giftIds['code'] == 1) {
            foreach ($giftIds['data'] as $k => $v) {
                $res = Db::name('gift')->where('id', $v)->update(['status' => 4]); //分享回调

            }

            if ($res !== false) {
                $this->success('设置成功');
            } else {
                $this->error('设置失败');
            }
        } else {
            $this->error($giftIds['msg'],$giftIds['data']);
        }

    }

    public function testQrcode(){

        $order_sn = input('order_sn');
        $wx = new \wechat\Wx();
        $wxqrce = $wx->getQrCode($this->auth->id, $order_sn);
        echo json_encode($wxqrce);
    }


}